package com.vilynn.learning.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * Created by wangweilin on 2018/12/19.
 */
public class NioTest {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();

        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.configureBlocking(false);
        channel.bind(new InetSocketAddress("127.0.0.1", 3389));

        SocketChannel accept = channel.accept();

        channel.register(selector, SelectionKey.OP_ACCEPT);
//        channel.register(selector, SelectionKey.OP_CONNECT);
//        channel.register(selector, SelectionKey.OP_READ);
//        channel.register(selector, SelectionKey.OP_WRITE);

        Handler handler = new Handler();
        while (true) {

            int select = selector.select(2000);
            if(select == 0){
                System.out.println("2s无请求，继续循环");
                continue;
            }
            System.out.println("开始处理请求。。。");
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if(key.isAcceptable()){
                    System.out.println("开始接收请求。。。");
                    handler.handleAccept(key);
                }
                if(key.isConnectable()){
                    System.out.println("连接请求。。。");
                }
                if(key.isWritable()){
                    System.out.println("写请求。。。");
                }
                if(key.isReadable()){
                    System.out.println("读请求。。。");
                    handler.handleRead(key);
                }
                // 处理完后，移除
                iterator.remove();
            }
        }

    }

    private static class Handler {
        private int bufferSize = 1024;
        private String localCharset = "utf-8";

        public void handleAccept(SelectionKey key) throws IOException {
            SocketChannel accept = ((ServerSocketChannel) key.channel()).accept();
            accept.configureBlocking(false);
            accept.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
        }

        public void handleRead(SelectionKey key) throws IOException {
            SocketChannel channel = (SocketChannel)key.channel();
            ByteBuffer buffer = (ByteBuffer)key.attachment();
            buffer.clear();
            if(channel.read(buffer) == -1){
                channel.close();
                return;
            }

            buffer.flip();
            String receiveStr = Charset.forName(localCharset).newDecoder().decode(buffer).toString();
            System.out.println("----" + receiveStr);

            String sendStr = "返回数据；；。。。萨达说";
            StringBuilder sb = new StringBuilder();
            sb.append("HTTP/1.1 200 OK\r\n")
                    .append("Content-Type: text/html;Charset=utf-8\r\n")
                    .append("\r\n")
                    .append(sendStr);
            ByteBuffer wrap = ByteBuffer.wrap(sb.toString().getBytes(localCharset));
            channel.write(wrap);
            channel.close();
        }
    }
}
